using System.Collections.Generic;
using System.IO;
using LitJson;
using UnityEngine;

/// <summary>
///     ���л��ͷ����л�Jsonʱ  ʹ�õ������ַ���
/// </summary>
public enum JsonType
{
    JsonUtlity,
    LitJson
}

/// <summary>
///     ʹ��json��������ʱ���Ӧ���ļ�������ȥƴд
/// </summary>
public static class PersistentDataPathName
{
    public static readonly string BAG = "bag";
}

/// <summary>
///     Json���ݹ����� ��Ҫ���ڽ��� Json�����л��洢��Ӳ�� �� �����л���Ӳ���ж�ȡ���ڴ���
///     ֧��list �� dictionary ���ֵ��keyҪʹ��string���͵�
///     ���Խ������ʹ�ã�list��dic��������
///     Ĭ��ʹ��litjson����ʵ��������
/// </summary>
public class JsonManager : Singleton<JsonManager>, ISingleton
{
    //ע���������ʵ�����ļ�����Ҫ���������ע�ᣬ���Ҳ���ʹ�ô������
    //�����������ļ�����������ܶ࣬����Ҫʹ���ֵ�
    private readonly List<string> registry = new() { "bag" };

    void ISingleton.Initialize()
    {
    }

    //�洢Json���� ���л�
    public void SaveData(object data, string fileName, JsonType type = JsonType.LitJson)
    {
        //ȷ���洢·��
        var path = Application.persistentDataPath + "/" + fileName + ".json";
        //���л� �õ�Json�ַ���
        var jsonStr = "";
        switch (type)
        {
            case JsonType.JsonUtlity:
                jsonStr = JsonUtility.ToJson(data);
                break;
            case JsonType.LitJson:
                jsonStr = JsonMapper.ToJson(data);
                break;
        }

        //�����л���Json�ַ��� �洢��ָ��·�����ļ���
        File.WriteAllText(path, jsonStr);
    }


    //��ȡָ���ļ��е� Json���� �����л�
    public T LoadData<T>(string fileName, JsonType type = JsonType.LitJson) where T : new()
    {
        //ȷ�����ĸ�·����ȡ
        //�������ж� Ĭ�������ļ������Ƿ���������Ҫ������ ����� �ʹ��л�ȡ
        var path = Application.streamingAssetsPath + "/" + fileName + ".json";
        //���ж� �Ƿ��������ļ�
        //���������Ĭ���ļ� �ʹ� ��д�ļ�����ȥѰ��
        if (!File.Exists(path))
            path = Application.persistentDataPath + "/" + fileName + ".json";
        //�����д�ļ����ж���û�� �Ǿͷ���һ��Ĭ�϶���
        if (!File.Exists(path))
            return new T();

        //���з����л�
        var jsonStr = File.ReadAllText(path);
        //���ݶ���
        var data = default(T);
        switch (type)
        {
            case JsonType.JsonUtlity:
                data = JsonUtility.FromJson<T>(jsonStr);
                break;
            case JsonType.LitJson:
                data = JsonMapper.ToObject<T>(jsonStr);
                break;
        }

        //�Ѷ��󷵻س�ȥ
        return data;
    }
}